using ManaMaple.Core;
using ManaMaple.Core.Extensions;
using ManaMaple.Core.HealthChecks;
using Serilog;
using Microsoft.AspNetCore.Http.Features;
using System.Net.Mime;

// 配置Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build())
    .CreateLogger();

try
{
    Log.Information("应用程序启动中...");
    
    var builder = WebApplication.CreateBuilder(args);
    
    // 使用Serilog作为日志提供程序
    builder.Host.UseSerilog();

    // Add services to the container.
    builder.Services.AddControllers();
    builder.Services.AddControllers().AddControllersAsServices();
    
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    // ManaMaple 核心服务（已包含监控、健康检查和日志配置）
    builder.Services.AddManaMapleCoreServices();
    builder.Host.AddManaMapleCoreHost();

    builder.Services.AddDistributedMemoryCache(); // 使用内存缓存
    builder.Services.AddHttpContextAccessor(); // 注入IHttpContextAccessor

    var app = builder.Build();

    // 配置HTTP请求管道
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    // 使用Serilog请求日志中间件
    app.UseSerilogRequestLogging();

    // ManaMaple 核心中间件
    app.UseManaMapleCoreMiddlewaree();
    app.AddManaMapleWebApplication();
    
    // 使用监控和健康检查终结点
    app.UseMonitoring();  // 使用自定义的监控中间件
    app.UseMonitoringEndpoints();  // 使用自定义的监控端点

    app.UseHttpsRedirection();

    #region 认证授权位置很重要
    // 认证
    app.UseAuthentication();
    // 授权
    app.UseAuthorization();
    #endregion

    app.MapControllers();

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "应用程序启动失败");
}
finally
{
    Log.CloseAndFlush();
}
